package summary;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/17 9:42
 * https://leetcode-cn.com/problems/restore-ip-addresses/
 */
public class Title93 {

    List<String> result = new ArrayList<>();
    LinkedList<String> list = new LinkedList<>();

    public List<String> restoreIpAddresses(String s) {
        backTracking(s, 0);
        return result;
    }

    private void backTracking(String s, int start) {
        if (start >= s.length() && list.size() == 4) {
            result.add(String.join(".", list));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (list.size() >= 4) {
                break;
            }
            String str = s.substring(start, i + 1);
            Integer num = Integer.valueOf(str);
            if (num >= 0 && num <= 255) {
                if (str.length() > 1 && str.charAt(0) == '0') {
                    break;
                }
            } else {
                break;
            }
            list.offer(str);
            backTracking(s, i + 1);
            list.removeLast();
        }
    }







    public static List<String> restoreIpAddresses1(String s) {
        List<String> result = new ArrayList<>();
        LinkedList<String> temp = new LinkedList<>();
        backTracking1(result, temp, s, 0);
        return result;
    }

    private static void backTracking1(List<String> result, LinkedList<String> temp, String s, int start) {
        if (start == s.length() && temp.size() == 4) {
            result.add(String.join(".", temp));
            return;
        }
        for (int i = start; i < s.length(); i++) {
            if (temp.size() >= 4) {
                break;
            }
            if (!isIpValid(s, start, i)) {
                break;
            }
            temp.offer(s.substring(start, i + 1));
            backTracking1(result, temp, s, i + 1);
            temp.removeLast();
        }
    }

    private static boolean isIpValid(String s, int start, int end) {
        String str = s.substring(start, end + 1);
        if (str.length() > 1 && str.charAt(0) == '0') {
            return false;
        }
        int ip = Integer.valueOf(str);
        return ip <= 255;
    }

    public static void main(String[] args) {
        restoreIpAddresses1("25525511135");
    }
}
